package com.wangp.mywrite.s_netty.nio.ch3.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.wangp.mywrite.s_netty.nio.ch1.ByteBufferUtil.debugAll;


/**
 * @description: TODO
 * @author tooStronger
 * @date 2023/3/16
 */
@Slf4j
public class AioFileChannel {
    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("D:\\data.txt"), StandardOpenOption.READ)) {
            // 参数1 bytebuffer
            // 参数2 读取的起始位置
            // 参数3 附件
            // 参数4 回调对象
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.info("read begin...");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    // read 成功
                    if(result!=0) {
                        log.info("read completed...");
                        attachment.flip();
                        debugAll(attachment);
                        attachment.clear();
                    }
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    // read 失败
                }
            });
            log.info("read end");
        } catch (IOException e) {
        }
        System.in.read();
    }
}
